package app.im;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.TextView;

import com.example.menhoo.toollibrary.common.assist.Check;
import com.example.menhoo.toollibrary.common.helper.MessageUtil;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.lidroid.xutils.bitmap.callback.BitmapLoadCallBack;
import com.lidroid.xutils.bitmap.callback.BitmapLoadFrom;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.util.LogUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import app.AutoFragment;
import application.AppApplication;
import application.HttpUrlConstant;
import custom.GridViewAdapter;
import fragment.IM2;
import interfaces.IReturnObject;
import mainUI.AppActivity;
import menhoo.com.i8officelibrary.R;
import model.AppModel;
import model.EmployeeItemDBModel;
import model.IMCvnDBModel;
import model.LoginUser;

/**
 * Created by yanglei on 17/1/8.
 */

public class IMGroupInfo extends AppActivity {
    public static final int Open_GroupName = 0x1003;
    //选择人员
    public static final int Open_AddAddressBook = 0x1002;
    public static final int Open_DelAddressBook = 0x1004;

    LinearLayout linearLayoutGroupName;

    LinearLayout linearLayoutDelMessage;

    TextView textViewGroupName;

    GridView gridView;

    Button btnTuiChu;

    boolean isClose=false;

    List<LoginUser> list = new ArrayList<>();
    MyGridViewAdapter adapter = null;
    String ID = null,GroupName=null,GroupDesc=null;
    ArrayList<String> EmplIdList = new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setRunSignalrService(false);
        try {
            ID =getIntent().getExtras().getString("ID");

        } catch (Exception e) {
            LogUtils.e(e.getMessage() + "");
        }
        super.onCreate(savedInstanceState);
        //
        setContentView(R.layout.im_group_info);
        try{
            btnTuiChu=(Button) findViewById(R.id.btnTuiChu);
            linearLayoutGroupName = (LinearLayout)findViewById(R.id.linearLayoutGroupName);
            linearLayoutDelMessage = (LinearLayout)findViewById(R.id.linearLayoutDelMessage);
            textViewGroupName = (TextView)findViewById(R.id.textViewGroupName);
            gridView = (GridView)findViewById(R.id.gridView);

            linearLayoutGroupName.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent it = new Intent(getApplicationContext(), IMEditGrouName.class);// 创建Intent对象
                    it.putExtra("GroupName", textViewGroupName.getText().toString());
                    it.putStringArrayListExtra("EmplIdList",EmplIdList);
                    startActivityForResult(it,Open_GroupName);
                }
            });

            linearLayoutDelMessage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            });
            btnTuiChu.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showSimpleDialogMessage("确定要退出该群组么？", new IReturnObject() {
                        @Override
                        public void returnResult(Object result) {
                            exitGroup(ID);
                        }
                    },true,true);
                }
            });

        }
        catch (Exception e){
            LogUtils.e(e.getMessage()+"");
        }


        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                LoginUser item = (LoginUser) parent.getAdapter().getItem(position);
                if(!item.userName.equalsIgnoreCase("item")){
                    if(item.userName.equalsIgnoreCase("add")){

                        AppModel appModel = new AppModel();
                        appModel.code="People";
                        appModel.type="internal";
                        appModel.name = "通讯录";

                        Bundle bundle = new Bundle();
                        bundle.putBoolean("IsMultiple", true);

                        ArrayList<EmployeeItemDBModel> selectList = new ArrayList<EmployeeItemDBModel>();
                        if(list!=null){
                            for(LoginUser var : list){
                                if(var.userName.equalsIgnoreCase("item") && !var.EmplID.equalsIgnoreCase(AppApplication.getUser().EmplID)){
                                    EmployeeItemDBModel edb = new EmployeeItemDBModel();
                                    edb.EmplID = var.EmplID;
                                    edb.Name = var.EmplName;
                                    selectList.add(edb);
                                }
                            }
                        }
                        if(selectList.size()>0){
                            bundle.putSerializable("SelectedList", selectList);
                        }


                        Intent it =new Intent(IMGroupInfo.this, AutoFragment.class);
                        it.putExtra("Model",appModel);
                        it.putExtra("IsReturnResult",true);
                        it.putExtra("TagBundle",bundle);
                        startActivityForResult(it, Open_AddAddressBook);
                    }
                    else if(item.userName.equalsIgnoreCase("del")){
                        //MessageUtil.showShortToast(IMGroupInfo.this,"del");
                        AppModel appModel = new AppModel();
                        appModel.code="People";
                        appModel.type="internal";
                        appModel.name = "通讯录";

                        Bundle bundle = new Bundle();
                        bundle.putBoolean("IsMultiple", true);

                        ArrayList<EmployeeItemDBModel> dataList = new ArrayList<EmployeeItemDBModel>();
                        if(list!=null){
                            for(LoginUser var : list){
                                if(var.userName.equalsIgnoreCase("item") && !var.EmplID.equalsIgnoreCase(AppApplication.getUser().EmplID)){
                                    EmployeeItemDBModel edb = new EmployeeItemDBModel();
                                    edb.EmplID = var.EmplID;
                                    edb.Name = var.EmplName;
                                    dataList.add(edb);
                                }
                            }
                        }
                        if(dataList.size()>0){
                            bundle.putSerializable("DataList", dataList);
                        }

                        Intent it =new Intent(IMGroupInfo.this, AutoFragment.class);
                        it.putExtra("Model",appModel);
                        it.putExtra("IsReturnResult",true);
                        it.putExtra("TagBundle",bundle);
                        startActivityForResult(it, Open_DelAddressBook);
                    }
                }
            }
        });


        hideContent();
        setTitle("群组详情");
        requestGroup(ID);
    }

    /**
     * 请求群主的详细信息
     */
    private void requestGroup(String id){
        RequestParams params = new RequestParams();
        params.addQueryStringParameter("id", id);
        params.addQueryStringParameter("isFullUsers", "true");
        Post(HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant.GetGroupById), params, new IReturnObject<String>() {
            @Override
            public void returnResult(String result) {
                if (result != null) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (jsonObject.getBoolean("Succeed")) {

                            JSONObject data = jsonObject.getJSONObject("Data");
                            String groupName = data.getString("GroupName");
                            String groupDesc = data.getString("Describe");
                            GroupDesc = groupDesc;
                            GroupName = groupName;
                            textViewGroupName.setText(groupName);

                            JSONArray Users = data.getJSONArray("Users");
                            for(int i=0;i<Users.length();i++){
                                JSONObject json = Users.getJSONObject(i);
                                String EmplName=json.getString("EmplName");
                                String EmplID=json.getString("EmplID");
                                String ImgUrl = json.getString("ImgUrl");

                                LoginUser item = new LoginUser();
                                item.userName="item";
                                item.EmplID = EmplID;
                                item.EmplName = EmplName;
                                item.Image = HttpUrlConstant.getWebSiteFullUrl(ImgUrl);

                                list.add(item);
                                EmplIdList.add(item.EmplID);
                            }

                            LoginUser add = new LoginUser();
                            add.userName="add";
                            add.EmplID="add";
                            list.add(add);
                            LoginUser del = new LoginUser();
                            del.userName="del";
                            del.EmplID="del";
                            list.add(del);


                            if(list.size()>0){
                                adapter = new MyGridViewAdapter(IMGroupInfo.this,list);
                                gridView.setAdapter(adapter);
                                setListViewHeightBasedOnChildren(gridView);
                                adapter.notifyDataSetChanged();
                            }

                        }
                    } catch (Exception ex) {
                        LogUtils.e(ex.getMessage() + "");
                    }
                }

                showContent();
            }
        });
    }
    /**
     * 请求群主的详细信息
     */
    private void requestUpdateGroup(){
        RequestParams params = new RequestParams();
        params.addQueryStringParameter("groupID", ID);
        params.addQueryStringParameter("groupName", GroupName);
        params.addQueryStringParameter("groupDesc", GroupDesc);
        params.addQueryStringParameter("emplIdList", com.example.menhoo.toollibrary.common.utils.StringUtil.join(EmplIdList,","));
        Post(HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant.UpdateGroupConversation), params, new IReturnObject<String>() {
            @Override
            public void returnResult(String result) {
                if (result != null) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (jsonObject.getBoolean("Succeed")) {
                            JSONObject data = jsonObject.getJSONObject("Data");
                            String groupName = data.getString("GroupName");
                            String groupDesc = data.getString("GroupDesc");
                            GroupDesc = groupDesc;
                            textViewGroupName.setText(groupName);

                            JSONArray Users = data.getJSONArray("Users");
                            EmplIdList.clear();
                            for(int i=0;i<Users.length();i++){
                                JSONObject json = Users.getJSONObject(i);

                                String EmplID=json.getString("EmplID");

                                EmplIdList.add(EmplID);
                            }
                            MessageUtil.showShortToast(IMGroupInfo.this,"更新成功");
                        }
                    } catch (Exception ex) {
                        LogUtils.e(ex.getMessage() + "");
                    }
                }

            }
        });
    }


    private void exitGroup(final String id){
        RequestParams params = new RequestParams();
        params.addQueryStringParameter("groupID", id);
        Post(HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant.ExitGroupConversation), params, new IReturnObject<String>() {
            @Override
            public void returnResult(String result) {
                if (result != null) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (jsonObject.getBoolean("Succeed")) {

                            isClose=true;
                            IM2.Is_Refresh=true;
                            try{
                                IMCvnDBModel item=getDB().findFirst(Selector.from(IMCvnDBModel.class).where("groupID","=",id));
                                if(item!=null){
                                    getDB().delete(item);
                                }

                            }
                            catch (Exception ex){}
                            MessageUtil.showShortToast(IMGroupInfo.this,"退出成功");
                            onBackPressed();

                        }
                    } catch (Exception ex) {
                        LogUtils.e(ex.getMessage() + "");
                    }
                }

                showContent();
            }
        });
    }


    class MyGridViewAdapter extends GridViewAdapter {


        public MyGridViewAdapter(Context context, List strList) {
            super(context, strList);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder=null;
            if(convertView==null){
                viewHolder = new ViewHolder();
                convertView= getLayoutInflater().inflate(R.layout.adapter_app_item,null);
                viewHolder.text=(TextView)convertView.findViewById(R.id.textView);
                viewHolder.img=(ImageView)convertView.findViewById(R.id.imageView);
                convertView.setTag(viewHolder);
            }
            else{
                viewHolder = (ViewHolder)convertView.getTag();
            }

            LoginUser model = (LoginUser)(getList().get(position));

            //hide时隐藏Text
            if(position != getHidePosition()) {
                if(model.userName.equalsIgnoreCase("item")){
                    viewHolder.text.setText(model.EmplName);
                    if(Check.isEmpty(model.Image)){
                        viewHolder.img.setImageResource(R.mipmap.untitled);
                    }
                    else{
                        getIconLoader().display(viewHolder.img, model.Image, new BitmapLoadCallBack<ImageView>() {
                            @Override
                            public void onLoadCompleted(ImageView imageView, String s, Bitmap bitmap, BitmapDisplayConfig bitmapDisplayConfig, BitmapLoadFrom bitmapLoadFrom) {
                                imageView.setImageBitmap(bitmap);
                            }

                            @Override
                            public void onLoadFailed(ImageView imageView, String s, Drawable drawable) {
                                imageView.setImageResource(R.drawable.load_failed);
                            }
                        });
                    }
                }
                else{
                    viewHolder.text.setText("");
                    if(model.userName.equalsIgnoreCase("add")){
                        viewHolder.img.setImageResource(R.mipmap.smiley_add_btn_pressed);

                    }
                    else if(model.userName.equalsIgnoreCase("del")){
                        viewHolder.img.setImageResource(R.mipmap.smiley_minus_btn_pressed);

                    }

                }


                convertView.setVisibility(View.VISIBLE);
            }
            else {
                convertView.setVisibility(View.GONE);
            }
            convertView.setId(position);

            return convertView;
        }

    }

    class ViewHolder{
        TextView text;
        ImageView img;
    }
    public static void setListViewHeightBasedOnChildren(GridView listView) {
        // 获取listview的adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        // 固定列宽，有多少列
        int col = 4;// listView.getNumColumns();
        int totalHeight = 0;
        // i每次加4，相当于listAdapter.getCount()小于等于4时 循环一次，计算一次item的高度，
        // listAdapter.getCount()小于等于8时计算两次高度相加
        for (int i = 0; i < listAdapter.getCount(); i += col) {
            // 获取listview的每一个item
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            // 获取item的高度和
            totalHeight += listItem.getMeasuredHeight();
        }

        // 获取listview的布局参数
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        // 设置高度
        params.height = totalHeight;
        // 设置margin
        ((ViewGroup.MarginLayoutParams) params).setMargins(10, 10, 10, 10);
        // 设置参数
        listView.setLayoutParams(params);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode== Activity.RESULT_OK && requestCode==Open_GroupName){
            try{
                String Data = data.getStringExtra("Data");
                GroupName = Data;
                textViewGroupName.setText(GroupName);
                requestUpdateGroup();
            }
            catch (Exception e){
                LogUtils.e(e.getMessage()+"");
            }

        }
        else if(resultCode== Activity.RESULT_OK && requestCode==Open_AddAddressBook){
            ArrayList<EmployeeItemDBModel> listData = (ArrayList<EmployeeItemDBModel>)data.getSerializableExtra("Data");
            if(listData!=null){
                list.clear();
                EmplIdList.clear();

                boolean hasCurrUser=false;
                for(EmployeeItemDBModel item : listData){
                    if(item.EmplID.equalsIgnoreCase(AppApplication.getUser().EmplID)){
                        hasCurrUser=true;
                    }

                    LoginUser user = new LoginUser();
                    user.userName="item";
                    user.EmplID = item.EmplID;
                    user.EmplName = item.Name;
                    Map<String,String> parm= new HashMap<String,String>();
                    parm.put("emplid", item.EmplID);
                    user.Image = HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant.doShowPhoto,parm);
                    list.add(user);
                    EmplIdList.add(item.EmplID);
                }
                if(!hasCurrUser){
                    LoginUser user = AppApplication.getUser();
                    Map<String,String> parm= new HashMap<String,String>();
                    parm.put("emplid", user.EmplID);
                    user.Image = HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant.doShowPhoto,parm);
                    user.userName = "item";
                    list.add(0,user);
                    EmplIdList.add(user.EmplID);
                }

                LoginUser add = new LoginUser();
                add.userName="add";
                add.EmplID="add";
                list.add(add);
                LoginUser del = new LoginUser();
                del.userName="del";
                del.EmplID="del";
                list.add(del);


                if(list.size()>0){
                    adapter = new MyGridViewAdapter(IMGroupInfo.this,list);
                    gridView.setAdapter(adapter);
                    setListViewHeightBasedOnChildren(gridView);
                    adapter.notifyDataSetChanged();
                }
                requestUpdateGroup();
            }
        }
        else if(resultCode== Activity.RESULT_OK && requestCode==Open_DelAddressBook){
            try{
                ArrayList<EmployeeItemDBModel> listData = (ArrayList<EmployeeItemDBModel>)data.getSerializableExtra("Data");
                if(listData!=null){
                    if(EmplIdList.size()==listData.size()){

                        MessageUtil.showShortToast(IMGroupInfo.this,"请不要情况群组中的所有人员");
                        return;
                    }
                    ArrayList<LoginUser> delList = new ArrayList<>();
                    for(EmployeeItemDBModel item : listData){
                        for(LoginUser user : list){
                            if(user.EmplID.equalsIgnoreCase(item.EmplID)){
                                //list.remove(user);
                                delList.add(user);
                            }
                        }
                        if(EmplIdList.contains(item.EmplID)){
                            EmplIdList.remove(item.EmplID);
                        }
                    }

                    list.removeAll(delList);

                    if(list.size()>0){
                        adapter = new MyGridViewAdapter(IMGroupInfo.this,list);
                        gridView.setAdapter(adapter);
                        setListViewHeightBasedOnChildren(gridView);
                        adapter.notifyDataSetChanged();
                    }
                    requestUpdateGroup();
                }
            }
            catch (Exception ex){
                LogUtils.d(ex.getMessage()+"");
            }

        }
    }

    @Override
    public void onBackPressed() {

        Intent it = new Intent();
        it.putExtra("GroupName",GroupName);
        it.putExtra("UserCount",EmplIdList.size());
        it.putExtra("IsClose",isClose);

        setResult(Activity.RESULT_OK, it);
        super.onBackPressed();
    }
}
